﻿using System;
using audio.Helper.TcpSocket;

namespace audio
{



    /// <summary>
    /// 通信服务
    /// </summary>
    public class Client
    {
        #region 私有字段

        /// <summary>
        /// 通信
        /// </summary>
        private TcpClient _commun;

        /// <summary>
        /// ip
        /// </summary>
        private readonly string _ip;
        /// <summary>
        /// 端口
        /// </summary>
        private readonly int _port;



        #endregion

        #region 属性



        /// <summary>
        /// 上次心跳返回时间
        /// </summary>
        public DateTime LastTime { get; private set; }
        ///// <summary>
        ///// 通讯状态
        ///// </summary>
        //public bool CommunicationState { get; private set; }
        /// <summary>
        /// 保持连接（超时时间） 
        /// </summary>
        public short KeepAlive { get; set; }

        #endregion


        ///  <summary>
        /// 构造方法
        ///  </summary> 
        ///  <param name="ip"></param>
        ///  <param name="port"></param>
        ///  <param name="keepAlive"></param> 
        public Client(string ip, int port, short keepAlive)
        {
            _ip = ip;
            _port = port;
            KeepAlive = keepAlive;


        }

        #region  连接 基础方法


        /// <summary>
        /// 连接
        /// </summary>
        public bool Connection()
        {
            try
            {
                if (_commun == null)
                {
                    _commun = new TcpClient(_ip, _port, 1, true);
                    _commun.ReceiveEvent += _commun_ReceiveEvent;
                    return _commun.TryConnect();
                }

            }
            catch (Exception)
            {
                // ignored
            }
            return false;
        }

        public bool Close()
        {

            return _commun.Close();
        }

        public Action<byte[]> ReceiveEvent;

        /// <summary>
        /// 接收
        /// </summary>
        /// <param name="data"></param>
        private void _commun_ReceiveEvent(byte[] data)
        {
            try
            {
                LastTime = DateTime.Now;
                if (data != null)
                {
                    ReceiveEvent.Invoke(data);
                }
            }
            catch (Exception)
            {
                //_logManager?.Error(ex);
            }

        }


        public bool Send(byte[] data)
        {
            return _commun.Send(data);
        }


        #endregion


    }
}
